<template>
  <div class="preview-cad-container">
    <div class="loading-warp" v-if="displayValue != 4 || loading">
      <a-spin size="large" />
      <div class="tip" v-if="displayValue != 4">{{ displayName }}</div>
    </div>
    <div class="BlackHole-container" ref="blackHoleContainer"></div>
  </div>
</template>
<script>
import { axios } from "@/utils/request";
import { canvasHolder } from "@/blackHoleTools/CanvasHolder";
export default {
  data() {
    return {
      loading: false,
      cadSource: {},
      //
      displayName: "",
      displayValue: 0,
    };
  },
  mounted() {
    this.$nextTick((_) => {
      let { uuid, fileName } = this.$route.query;
      document.title = fileName;
      if (uuid) {
        this.getSetModelData(uuid);
      }
    });
  },
  methods: {
    //初始化引擎引擎系统
    initEngine() {
      let canvasDom = canvasHolder.get();
      if (!canvasDom) {
        canvasDom = canvasHolder.create();
        document.body.appendChild(canvasDom);
      }
      window.BlackHole3D = window.BlackHole3D ? window.BlackHole3D : {};
      window.BlackHole3D["canvas"] = canvasDom;
      if (typeof window.BlackHole3D.RealBIMWeb === "undefined") {
        window.BlackHole3D = window.CreateBlackHoleWebSDK(window.BlackHole3D);
      }
    },

    //引擎系统初始化完成回调
    onSystemReady() {
      let containerBox = this.$refs["blackHoleContainer"];
      var sysInfo = new BlackHole3D.RESysInfo();
      //相对于html页面的RealBIMWeb_Worker.js的路径
      sysInfo.workerjsPath = "./blackhole/RealBIMWeb_Worker.js";
      //初始化图形窗口的宽度
      sysInfo.renderWidth = containerBox?.clientWidth;
      //初始化图形窗口的高度
      sysInfo.renderHieght = containerBox?.clientHeight;
      //引擎调用的公共资源的路径
      sysInfo.commonUrl =
        "http://203.156.230.22:9012/default.aspx?dir=url_res03&path=res_gol001";
      //引擎资 源发布服务配套的用户名、密码
      sysInfo.userName = "bjadmin";
      sysInfo.passWord = "Bj@123456.";
      //表示主窗口的名称,对应document.title，默认值 "BlackHole"
      sysInfo.mainWndName = document.title;
      //开始执行场景初始化，加载公共资源
      BlackHole3D.initEngineSys(sysInfo);
      console.log("引擎系统初始化完成", sysInfo, BlackHole3D);
    },

    //查询BIM地址
    getSetModelData(uuid = "") {
      this.loading = true;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/bimCadFile/project/cadFile/list?uuid=${uuid}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.cadSource = res?.data?.[0] ?? {};
            this.displayValue = this.cadSource?.status?.value ?? 0;
            this.displayName = this.cadSource?.status?.displayName ?? "";
            this.addEventListener();
            this.initEngine();
            resolve();
          })
          .catch((_) => {
            this.status = {};
            this.cadSource = {};
            reject();
          })
          .finally((_) => {});
      });
    },

    //系统引擎创建完成回调【加载模型资源】
    onEngineCreated() {
      let { unit } = this.$route.query;
      try {
        let { resourcesAddress } = this.cadSource;
        let dom = this.$refs.blackHoleContainer;
        let BlackHole3D = window.BlackHole3D;
        canvasHolder.moveCanvasToTarget(this.$refs.blackHoleContainer);
        BlackHole3D.m_re_em_window_width = dom.clientWidth;
        BlackHole3D.m_re_em_window_height = dom.clientHeight;
        BlackHole3D.Coordinate.setEngineWorldCRS("EPSG:3857");
        BlackHole3D.setViewMode(
          BlackHole3D.REVpTypeEm.None,
          BlackHole3D.REVpTypeEm.CAD,
          BlackHole3D.REVpRankEm.Single
        );
        BlackHole3D.CAD.loadCAD(
          resourcesAddress,
          BlackHole3D.RECadUnitEm[unit ?? "CAD_UNIT_Meter"],
          1.0
        );
      } catch (error) {}
    },

    //bim事件监听
    addEventListener() {
      document.addEventListener("RESystemReady", this.onSystemReady);
      document.addEventListener("RESystemEngineCreated", this.onEngineCreated);
      //场景模型加载完成回调
      document.addEventListener("RECADLoadFinish", (_) => {
        this.loading = false;
        //设置系统UI
        this.setSystemUI();
      });
      window.addEventListener("resize", this.onResize);
    },

    //设置系统UI
    setSystemUI() {
      try {
        BlackHole3D.Graphics.setGeoCoordVisible(false);
        BlackHole3D.Graphics.setSysUIPanelVisible(true);
        BlackHole3D.Graphics.setSysPanelUIDockArea(3);
        BlackHole3D.Camera.resetCamLocate();
        BlackHole3D.Camera.resetCamBound();
      } catch (error) {}
    },

    //监听窗口尺寸变化
    onResize() {
      let box = this.$refs["blackHoleContainer"];
      if (box) {
        window.BlackHole3D.m_re_em_window_width = window.innerWidth;
        window.BlackHole3D.m_re_em_window_height = window.innerHeight;
      }
    },

    //卸载
    releaseEngine() {
      document.removeEventListener("REDataSetLoadFinish", () => {});
      document.removeEventListener("RESystemReady", () => {});
      if (typeof window.BlackHole3D?.releaseEngine != "undefined") {
        canvasHolder.moveCanvasToBody();
        window.BlackHole3D?.releaseEngine();
        window.BlackHole3D = null;
      }
    },
  },
  beforeDestroy() {
    this.releaseEngine();
  },
};
</script>
<style lang="less" scoped>
.preview-cad-container {
  width: 100%;
  height: 100%;
  position: relative;
  .loading-warp {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    .tip {
      font-family: Microsoft YaHei, Microsoft YaHei;
      font-weight: 400;
      font-size: 16px;
      color: #fff;
      line-height: 50px;
    }
  }
  .BlackHole-container {
    width: 100%;
    height: 100%;
  }
}
</style>
